/**
 * 执行log的建立与记录
 */
;(function(g){

  if (g.wxqfzsLog) return;
  var log = g.wxqfzsLog = {};


  /**
   * 记录log
   */
  log.log = function(content, type)
  {
    type = type || 'info';
    var time = wxqf_common.getDate();
    var html = '<p><span class="wxqfzs-time">'+time+'</span><span class="wxqfzs-content '+type+'">'+content+'</span></p>';
    var logList = $('#wxqfzsLog .logList');
    logList.append(html);
    logList.scrollTop(logList[0].scrollHeight+100);
    return this;
  };

  log.show = function(task)
  {
    if (!$('#wxqfzsLog').length) {
      var msgHtml = task && task.messageHtml || '';
      var html = '\
      <div class="wxqfzs-page-tips success" id="wxqfzsLog" style="display:none;">\
        <div class="wxqfzs-inner">\
          <h1 class="wxqfzs-log-title">微信群发助手-状态栏<!--span style="color:#C70000;">（特别提醒：消息发送期间请勿关闭此页面）</span--></h1>\
          <div class="msgDetail wxqfzs-msg-detail">'+msgHtml+'</div>\
          <div class="logList wxqfzs-log-list"></div>\
          <div class="logStatus wxqfzs-log-status"></div>\
        </div>\
      </div>';
      $('body').append(html);
    }
    $('#wxqfzsLog').fadeIn();
    return this;
  };

  log.clear = function()
  {
    if ($('#wxqfzsLog').length) {
      $('#wxqfzsLog .logList').html('');
      $('#wxqfzsLog .logStatus').html('');
      $('#wxqfzsLog .msgDetail').html('');
    }
    return this;
  };

  log.hide = function()
  {
    $('#wxqfzsLog').fadeOut();
    return this;
  };

  log.displayStatus = function()
  {
    wxqf_common.api('messageGetDetail', {}, function(ret){
      if (!ret.result) return false;
      var total = ret.data.leftNum + ret.data.sentNum;

      var text = "待发送：" + ret.data.leftNum;
      text += " | 已发送：" + ret.data.sentNum;
      text += " | 发送中：" + ret.data.runningNum;
      text += " | 发送失败：" + ret.data.failedNum;

      // 计算时间 剩余数量 * 每次发送间隔时间 / 每次发送数量
      var leftTime = ret.data.leftNum*ret.data.config.sendTime / ret.data.config.sendCount;
      var unit = "秒";
      if (leftTime > 60) {
        leftTime = leftTime / 60;
        unit = "分钟";
        if (leftTime > 60) {
          leftTime = leftTime / 60;
          unit = "小时";
        }
      }
      leftTime = leftTime.toFixed(1);
      text += " | 预计["+leftTime+unit+"]后发送完毕";

      $('#wxqfzsLog .logStatus').text(text);
    });
    return this;
  };

})(window);

// 绑定关闭按钮
$(function(){
  $('#wxqfzsCloseLogBtn').live('click', function(){
    wxqfzsLog.hide();
  });
});